/**
 * 入参
 *  type：1-指令新增   2-簿记新增    3.1-指令详情   3.2-簿记详情  4-交收 11-组合试算
    info：type=3时，需回填字段
    onRef：组件指针
    getInfo：通过onRef，调用getInfo方法，获取各字段的值，在getInfo中完成校验，若校验不通过，返回undefined
    reset：通过onRef，调用reset方法，清空页面字段
    productOnChange：产品变更事件，输出当前产品ID，若无则为undefined；
    portfolioOnChange：组合变更事件，输出当前组合ID，若无则为undefined；
    tradingcodeOnChange：证券代码变更事件，输出当前证券code，若无则为undefined。
 */
import React, { PureComponent } from 'react';
import { FormGroup, DATA_ENTRY, codeType } from '../../../../comps';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { message } from 'antd';
import { connect } from 'dva';
import investmentType from './config';
import { calculateFee } from '../../../../utils/commonFunc';
import { times, divide } from 'number-precision';

class OrderFormC extends PureComponent {
  static defaultProps = {
    onRef: () => {},
    portfolioOnChange: () => {},
    productOnChange: () => {},
    tradingOnChange: () => {},
  };

  state = {
    direction: '1', // 1-买入 2-卖出 3-展期
    info: undefined, // 详情
    type: undefined, // 当前指令的类型
    SecuritiesCode: undefined, // 证券代码val值
    secuabbr: undefined, // 证券代码名字
    investmentTypeList: [...investmentType], // 投资类型下拉
    feeData: {
      // 费用自动计算条件
      productId: undefined,
      portfolioid: undefined,
      tradingCode: undefined,
      exchangecode: undefined, // 交易市场
      sectype: 'zcgl',
      orderside: '1', // 交易方向
      price: undefined,
    },
  };

  componentDidMount() {
    this.props?.onRef && this.props?.onRef(this);
    this.setState({
      direction: this.props?.info?.direction,
      feeData: {
        ...this.state.feeData,
        orderside: this.props?.info?.direction || '1',
      },
    });
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    if (JSON.stringify(nextProps.info) != JSON.stringify(this.props.info)) {
      this.setState({
        direction: nextProps?.info?.direction,
        feeData: {
          ...this.state.feeData,
          orderside: nextProps?.info?.direction || '1',
        },
      });
    }
  }

  // 费用自动计算
  changeFeeCalculate = (type, data) => {
    const {
      form: { setFieldsValue },
    } = this.formContent.props;
    if (this.props.type == '3' || this.props.type == '4') return; // 详情不计算
    if (data == undefined) {
      setFieldsValue({ fee: undefined });
      this.changeFee();
      if (type == 'tradingCode') {
        this.setState({ feeData: { ...this.state.feeData, tradingCode: undefined } });
      } else if (type == 'productId') {
        this.setState({ feeData: { ...this.state.feeData, productId: undefined, portfolioid: undefined } });
      } else {
        this.setState({ feeData: { ...this.state.feeData, [type]: undefined } });
      }
    } else if (type == 'tradingCode') {
      this.setState({ feeData: { ...this.state.feeData, tradingCode: data?.tradingCode } }, () => {
        const fee = calculateFee(this.state.feeData);
        fee.then((r) => {
          setFieldsValue(
            { fee: r },
            this.setState({ fee: r }, () => this.changeFee(r)),
          );
        });
      });
    } else {
      this.setState({ feeData: { ...this.state.feeData, [type]: data } }, () => {
        const fee = calculateFee(this.state.feeData);
        fee.then((r) => {
          setFieldsValue(
            { fee: r },
            this.setState({ fee: r }, () => this.changeFee(r)),
          );
        });
      });
    }
  };

  // 费用修改
  changeFee = (e) => {
    this.setState({
      fee: e || 0,
    });
  };

  // 组合改变
  groupOnChange = (value) => {
    // 抛出组合id
    let val;
    if (value) val = value.key;
    this.props.portfolioOnChange(value);
  };

  // 证券代码切换
  securitiesCodeChange = (value) => {
    const { info } = this.props;
    if (info) return; // 详情时不进入判断
    this.setState(
      {
        SecuritiesCode: value ? value.secucode : undefined,
        secuabbr: value ? value.secuabbr : undefined,
        feeData: {
          ...this.state.feeData,
          exchangecode: value ? value.exchangeCode : null,
          tradingCode: value ? value.tradingCode : null,
        },
      },
      () => {
        this.changeFeeCalculate('tradingCode', value ? value : undefined);
      },
    );
    this.props.tradingOnChange(value);
  };

  // 获取当前表单数据 并校验
  getInfo = () => {
    const {
      user: { currentUser },
      money = {},
      position = {},
      type,
    } = this.props;
    const {
      form: { validateFieldsAndScroll },
    } = this.formContent.props;
    let query;
    validateFieldsAndScroll((err, fieldsValue) => {
      if (!err) {
        // if (this.state.loadingFee) {
        //   message.warning('费用还在计算中,请稍后重试!')
        //   return
        // }

        if (type !== 2) {
          // 簿记不再前端验资验券
          // 【交易方向】为“买入”时，需要验资，【交易总额】需小于T+0可用，若大于，则提示“【交易总额】不能大于T+0可用”；
          if (fieldsValue.direction == '1') {
            fieldsValue.parValueTotal = parseFloat(Number(fieldsValue.parValueTotal.toFixed(2))); // 精度丢失问题
            if (fieldsValue.parValueTotal > (money.t0 || 0)) {
              message.warning('交易总额不能大于T+0可用!');
              return;
            }
          }
          // 【交易方向】为“卖出”时，需要验券，【交易数量】需小于可用数量，若大于，则提示“【交易数量】不能大于可用数量”；
          if (fieldsValue.direction == '2') {
            if (fieldsValue.amount > (position.available || 0)) {
              message.warning('交易数量不能大于可用数量!');
              return;
            }
          }
        }
        query = fieldsValue;
        query.userid = currentUser.userId;
        query.username = currentUser.name;
        query.tradingcode = this.state.feeData.tradingCode;
        query.exchangeCode = this.state.feeData.exchangecode;
        query.secuabbr = this.state.secuabbr;
        query.fee = 0; // 费用计算逻辑未完全梳理清楚，后续用户有真正需求时再添加费用计算相关逻辑
        delete query.zqdm;
      }
    });
    return query;
  };

  // 重置页面数据 取消
  reset = () => {
    const { form } = this.formContent.props;
    this.props.portfolioOnChange(undefined);
    this.props.tradingOnChange(undefined); // 重置组合id和证券代码
    this.setState({
      info: undefined, // 详情
      type: undefined, // 当前指令的类型
      SecuritiesCode: undefined, // 证券代码val值
      secuabbr: undefined,
      feeData: {
        // 费用自动计算条件
        productId: undefined,
        portfolioid: undefined,
        tradingCode: undefined,
        sectype: 'zcgl',
        orderside: undefined,
      },
      price: undefined,
      amount: undefined,
      direction: '1',
    });
    form.resetFields();
  };

  // 设置投资类型下拉 并确定默认值
  setSelectList = () => {
    // 以收取该金融资产合同现金流量为目的	是	AC
    // 以收取该金融资产合同现金流量为目的	否	FVTPL
    // 以收取该合同现金流量及出售金融资产为目的	是	FVOCI
    // 以收取该合同现金流量及出售金融资产为目的	否	FVTPL
    // 其他	是 or 否	FVTPL
    const {
      form: { setFieldsValue },
    } = this.formContent.props;
    const { direction } = this.state;
    if (direction == '1') {
      // 交易方向为买入
      setFieldsValue({
        investmentType: undefined,
      });
    } else if (direction == '2') {
      // 交易方向卖出 请求新的接口
      setTimeout(() => {
        setFieldsValue({
          investmentType: this.props.investmentType,
        });
      }, 500);
    }
  };

  // 改变某个数值得时候,影响另外得值
  changeValue = (e) => {
    const { type, info } = this.props;
    if (info) return; // 详情不进入
    // console.log(info,this.state.feeData,'info')
    // 当初始化进入的时候 可能有值可能没值
    this.setState(
      {
        direction: e?.value,
        feeData: {
          ...this.state.feeData,
          orderside: e?.value,
          price: undefined,
        },
      },
      () => {
        if (type < 3 || type == 12) {
          // 交易方向改变 对投资类型的影响 1买入 2卖出
          this.setSelectList();
        }
        if (this.formContent) {
          const {
            form: { setFieldsValue },
          } = this.formContent.props;
          setFieldsValue({
            price: undefined,
            amount: undefined,
            parValueTotal: undefined,
            fee: undefined,
            investmentType: 'FVTPL',
          });
        }
      },
    );
  };

  // 交易总额=交易价格 * 交易数量
  changeNum = (e, type) => {
    const {
      form: { setFieldsValue, getFieldValue },
    } = this.formContent.props;
    const data = getFieldValue(type);
    this.setState(
      {
        [type]: data,
      },
      () => {
        if (getFieldValue('price')) {
          if (getFieldValue('amount')) {
            setFieldsValue({
              parValueTotal: Number(times(getFieldValue('price') || 0, getFieldValue('amount') || 0).toFixed(2)), // 交易总额=交易价格 * 交易数量
            });
            this.setState(
              {
                feeData: {
                  ...this.state.feeData,
                  price: Number(times(getFieldValue('price') || 0, getFieldValue('amount') || 0).toFixed(2)),
                },
              },
              () => {
                this.changeFeeCalculate('price', Number(times(getFieldValue('price') || 0, getFieldValue('amount') || 0).toFixed(2)));
              },
            );
          } else {
            setFieldsValue({ parValueTotal: null, fee: undefined });
            this.setState({
              feeData: {
                ...this.state.feeData,
                price: null,
              },
            });
          }
        } else {
          setFieldsValue({ parValueTotal: null, fee: undefined });
          this.setState({
            feeData: {
              ...this.state.feeData,
              price: null,
            },
          });
        }
      },
    );
  };

  // 交易总额更改
  changePrice = (e) => {
    const {
      form: { setFieldsValue, getFieldValue },
    } = this.formContent.props;
    e.persist();
    // 反计算 改变交易价格
    this.setState(
      {
        feeData: {
          ...this.state.feeData,
          price: e.target.value.replace(/[^\d\.]/g, ''), // 交易总额
        },
      },
      () => {
        setFieldsValue({
          price: divide(e.target.value.replace(/[^\d\.]/g, '') || 0, getFieldValue('amount') || 0).toFixed(2), // 交易价格
        });
        this.changeFeeCalculate('price', e.target.value.replace(/[^\d\.]/g, ''));
      },
    );
  };

  // form表单渲染
  formRender = () => {
    const { type, info } = this.props;
    const { direction } = this.state;
    let disabled;
    if (type == 3 || type == 4) {
      // 3-4得情况下 是详情
      disabled = true;
    } else {
      disabled = false;
    }
    return (
      <div className={'formOrder'}>
        <FormGroup
          autoLayout={false}
          onRef={(ref) => (this.formContent = ref)}
          dataSource={[
            {
              type: DATA_ENTRY.PRODUCTGROUPSEP,
              disabled,
              title: ['产品', '组合'],
              initialValue: info ? [info.productid, info.portfolioid] : undefined,
              authority: 'write',
              multipleGroup: false,
              dataIndex: ['productid', 'portfolioid'],
              rules: [[{ required: true, message: '请选择产品!' }], [{ required: true, message: '请选择组合!' }]],
              groupOnChange: (e) => {
                this.groupOnChange(e);
                this.changeFeeCalculate('portfolioid', e?.key);
              },
              productOnChange: (e) => {
                // 改变产品 组合就没了
                this.setState(
                  {
                    feeData: {
                      ...this.state.feeData,
                      portfolioid: undefined,
                    },
                  },
                  () => {
                    this.changeFeeCalculate('productId', e?.key);
                    this.props.productOnChange(e); // 向外抛出产品code
                  },
                );
              },
              allowClear: false,
              exist: 1,
              span: 16,
              controlLabelSpan: 6,
              tradeModel: type == 1 || type == 2 ? ['BOOKKEEPING_MODE', 'COMMAND_MODE'] : undefined, // 不包含估值解析和估值对接的产品
            },
            {
              type: DATA_ENTRY.SECURITIESCODE,
              span: 8,
              title: '证券代码',
              initialValue: info ? `${info.exchangeCode}-${info.tradingcode}` : undefined,
              dataIndex: 'tradingCode',
              codeType: codeType.zgtzptPlan,
              onChange: (e) => this.securitiesCodeChange(e),
              disabled,
              rules: [{ required: true, message: '请选择证券代码!' }],
              controlLabelSpan: 6,
              // queryItems={{ time: moment(new Date()).format('YYYY-MM-DD'), exchangeCode: '162,166' }}
            },
            {
              dataIndex: 'direction',
              title: '交易方向',
              type: DATA_ENTRY.TRADINGDIRECT,
              businessType: '20',
              initialValue: info?.direction || '1',
              span: 8,
              disabled,
              appType: info ? '2' : undefined,
              rules: [{ required: true, message: '请选择!' }],
              onChange: this.changeValue,
              controlLabelSpan: 6,
              // 响应【产品】【组合】【证券代码】【交易方向】的变更，当都不为undefined时，调用接口
            },
            {
              dataIndex: 'price',
              title: '交易价格',
              type: DATA_ENTRY.INPUTNUMBER,
              initialValue: info?.price,
              unit: '元',
              precision: 2,
              disabled,
              splitStyle: true,
              rules: [{ required: true, message: '请输入数字!' }],
              min: 0.01,
              onChange: (e) => {
                this.changeNum(e, 'price');
              },
              span: 8,
              controlLabelSpan: 6,
            },
            {
              dataIndex: 'amount',
              title: '交易数量',
              type: DATA_ENTRY.INPUTNUMBER,
              initialValue: info?.amount,
              unit: '份',
              precision: 2,
              splitStyle: true,
              disabled,
              rules: [{ required: true, message: '请输入数字!' }],
              min: 0.01,
              onChange: (e) => {
                this.changeNum(e, 'amount');
              },
              span: 8,
              controlLabelSpan: 6,
            },
            {
              dataIndex: 'parValueTotal',
              title: '交易总额',
              type: DATA_ENTRY.INPUTNUMBER,
              unit: '元',
              disabled,
              splitStyle: true,
              precision: 2,
              initialValue: info?.parValueTotal ? Number(info?.parValueTotal.toFixed(2)) : null, // 交易总额=交易价格 * 交易数量
              rules: [{ required: true, message: '请输入数字!' }],
              min: 0.01,
              onBlur: (e) => this.changePrice(e),
              span: 8,
              controlLabelSpan: 6,
            },
            // {
            //   dataIndex: 'fee',
            //   title: '费用',
            //   type: DATA_ENTRY.INPUTNUMBER,
            //   unit:'元',
            //   disabled:disabled,
            //   precision:2,
            //   initialValue:info?.fee,
            //   // rules: [{required: true,message: '请输入数字!'}],
            //   span:8,
            //   controlLabelSpan:6
            // },
            {
              dataIndex: 'investmentType',
              title: '投资类型',
              type: DATA_ENTRY.SELECT,
              initialValue: info ? info.investmentType : 'FVTPL',
              span: 8,
              dataSource: investmentType,
              disabled: type == '3' || type == '4' ? true : direction == 2,
              controlLabelSpan: 6,
            },
            {
              dataIndex: 'remark',
              title: '备注',
              type: DATA_ENTRY.INPUT,
              showTextArea: true,
              disabled,
              initialValue: info?.remark,
              span: 24,
              controlLabelSpan: 2,
              max: 100,
            },
          ]}
        />
      </div>
    );
  };

  render() {
    return <div>{this.formRender()}</div>;
  }
}
export default connect(({ userM: user }) => ({ user }))(Form.create()(OrderFormC));
